//商品详情页面
//获取商品id
function getId() {
    let url = location.href
    url = url.substring(url.indexOf('?') + 1)
    let arr = url.split('=')
    let id = arr[1]
    return id
}

function loadDetail() {
    let id = getId()
    axios({
        method: 'get',
        url: 'http://api.yuguoxy.com/api/shop/find',
        params: {
            id,
        }
    }).then(response => {
        let data = response.data
        if (data.resultCode == 1) {
            let detailList = data.resultInfo
            showDetail(detailList)
            textDetail(detailList)

        }
    })
}
//展示商品详情图片
function showDetail(detailList) {
    //加载商品数据  图片数据 然后替换内容
    let data = detailList.list
    let str = ` <li class="b show">
            <img src="${detailList.picture}">
      </li>`
    $('.showBox').html(str)
    $('.bigPic').html(str)

    let smallStr =
        `
        <li><img src="${detailList.picture}" class="s"></li>
        <li><img src="${data[0]}" class="s"></li>
        <li><img src="${data[1]}" class="s"></li>
        <li><img src="${data[2]}" class="s"></li>
        <li><img src="${data[3]}" class="s"></li>
        `

    $('.smallPic').html(smallStr)
    $('.display').html(smallStr)

    onTab()
    init()

}
loadDetail()


//放大镜

// 全局变量
//左边的大盒子
const leftEle = $('.left')
//装小图片的盒子
let smallElis = $('.s')
//展示盒子里面的img
let showImgs = $('.showBox li img')
let bigImg = $('.b img')
//小图片切换
function onTab() {

    // 委托事件
    leftEle.on('mouseover', '.s', function () {

        //点击小图片的时候
        $('.s').removeClass('active')
        $(this).addClass('active')

    })

    $('.s').on('click', function () {
        let src = $(this).prop('src')
        console.log(src);
        console.log($('.showBox'));
        $('.showBox li img').prop('src', src)
        $('.b img').prop('src', src)
    })

}

//给展示盒子设置鼠标移动事件

function init() {
    const bigPicture = $('.bigPic .show img') //li
    const bigPicBox = $('.bigPic') //ul
    // 计算图片合适的宽高
    let w = $('.showBox').width() * bigPicBox.width() / $('.mask').width()
    //       展示盒子   *      放大镜盒子    /遮罩层    等于
    let h = $('.showBox').height() * bigPicBox.height() / $('.mask').height()
    bigPicture.width(w + 'px')
    bigPicture.height(h + 'px')

}

function followMove() {
    $('.showBox').on('mouseover', function () {
        const bigPicture = $('.bigPic .show') //li

        const bigPicBox = $('.bigPic') //ul
        $('.mask').css({
            display: 'block'
        })
        $('.bigPic').css({
            display: 'block'
        })
        $('.showBox').on('mousemove', function (e) {
            // e = e || window.event
            e = e

            // let target = $(e.target) || $(e.srcElement)
            //大图片上有一块遮罩层  移动鼠标的时候 通过e.clientX,Y获取鼠标的位置  减去遮罩层宽高的一半让鼠标到正中间
            //给遮罩层设置pointer-events:none解决闪烁问题
            //遮罩层随着鼠标的移动在展示中等图片的盒子上移动
            let x = e.offsetX - $('.mask').width() / 2
            let y = e.offsetY - $('.mask').height() / 2
            let xBorder = $('.showBox').width() - $('.mask').width()
            let yBorder = $('.showBox').height() - $('.mask').height()
            //边界问题
            if (x < 0) {
                x = 0
            }
            if (x > xBorder) {
                x = xBorder
            }
            if (y < 0) {
                y = 0
            }
            if (y > yBorder) {
                y = yBorder
            }

            $('.mask').css({
                left: `${x}px`,
                top: `${y}px`
            })

            let moveX = -(x * bigPicBox.width() / $('.mask').width())
            let moveY = -(y * bigPicBox.height() / $('.mask').height())

            bigPicture.css({
                left: `${moveX}px`,
                top: `${moveY}px`
            })
        })
    })

    $('.showBox').on('mouseout', function () {
        $('.mask').css({
            display: 'none'
        })
        $('.bigPic').css({
            display: 'none'
        })
    })

}
followMove()
// 展示商品文案详情
function textDetail(text) {
    let str = `<p>${text.shop}</p>
    <p>价格<span>￥${text.price}</span><span>月销量--</span></p>
    <p>优惠<span>最低折至0.1</span></p>
    <div class="operateBtn">
        数量
        <button name="minus">-</button>
        <input type="text" placeholder="1" value="1">
        <button name="plus">+</button>
        件
    </div>
    <div class="purchase">
        <span>立即购买</span>
        <span class="iconfont icon-gouwucheman addCart">加入购物车</span>
    </div>`

    $('.description').html(str)
    operate()
    addToCart(text)
}

function operate() {
    // 按钮点击加减
    $('button[name="plus"]').on('click', function () {
        let num = Number($('.description input').val())
        num++
        $('.description input').val(num)
    })

    $('button[name="minus"]').on('click', function () {
        let num = Number($('.description input').val())
        num--
        if (num < 1) {
            $('button[name="minus"]').prop('disabled')
        } else {
            $('.description input').val(num)
        }
    })
}

//加入购物车操作
function addToCart(text) {
    //获取用户的本地存储名称作为购物车名称
    let userString = localStorage.getItem('USER')
    let userList = JSON.parse(userString)

    let nameC = userList.username
    let cartStr = localStorage.getItem(`${nameC}`)
    let cartList = JSON.parse(cartStr) || []
    $('.addCart').on('click', function () {
        let num = Number($('.operateBtn input').val())
        let newProduct = {
            id: text.id,
            name: text.shop,
            url: text.picture,
            price: text.price,
            num, //数量
            singlePrice: text.price, //单个商品价格
            state: false, //状态
        }
        //如果当前商品已经存在
        let cartProduct = cartList.find(item => item.id == newProduct.id)
        if (cartProduct) {
            //已经存在数量加输入框数量
            let proNum = Number(cartProduct.num)
            cartProduct.num = proNum + num
            $('.operateBtn input').val('1')
        } else {
            //不存在，添加一条新数
            cartList.push(newProduct)
        }

        // 4. 持久化存储到localStorage
        localStorage.setItem(`${nameC}`, JSON.stringify(cartList))

        location.href = '../pages/cartList.html'

    })
}

//移入收藏夹
function tofavorite() {
    
}
// 跳转到购物车
$('.cart').on('click', function () {
    location.href = '../pages/cartList.html'
})